# -*-coding:utf-8 -*-
import os
import shutil
import process_file as pf
import subprocess
import extract_function_from_output as ex


key_model = "model_finetune"
key_add_path =  "FUT_path"
key_save = f"{key_model}_build"




success_num = 0
total_num = 0
prefix = "../../crates_crawler/crates/"

folder_path = '../../model_generation/dataset/test/'

def build_crate(crate_path):  
    try:  
        # 执行 cargo build，并将 stdout 和 stderr 都重定向到管道，设置超时为 120 秒  
        result = subprocess.run(  
            ['cargo', 'build'],  
            cwd=crate_path,  
            check=True,  
            stdout=subprocess.PIPE,  # 将标准输出重定向到管道  
            stderr=subprocess.STDOUT,  
            timeout=300  # 设置超时时间为 300 秒  
        )  
        # 将输出内容转换为字符串并返回  
        return True, result.stdout.decode('utf-8')  # 返回构建成功和输出内容  
    except subprocess.TimeoutExpired as e:  
        # 处理超时情况  
        return False, f"编译超时: {e.timeout} 秒达到。请检查您的项目。"  
    except subprocess.CalledProcessError as e:  
        # 返回构建失败并捕获 stderr 的内容  
        return False, e.stdout.decode('utf-8') if e.stdout else str(e)



for filename in os.listdir(folder_path):
    # 获取文件的完整路径
    file_path = os.path.join(folder_path, filename)
    if os.path.isfile(file_path) and filename.endswith('.json'):

        crate_path = f"{prefix}{filename[:-5]}"


        file_success_num = 0
        file_total_num = 0

        list_func_info = pf.read_json(file_path)
        list_compilation = []

        for dict_func_info in list_func_info:

            # 提取一个完整函数
            FUT_full = ex.extract_substring(dict_func_info.get(key_model, ""))
            if not FUT_full:
                continue
            add_path = dict_func_info[key_add_path]

            new_content = '\n' + FUT_full
            rs_original_content = pf.modify_rs_file(add_path, new_content)

            total_num += 1
            file_total_num += 1

            build_success, compilation_info = build_crate(crate_path)

            if build_success:
                dict_func_info[key_save] = "True"
                success_num += 1
                file_success_num += 1
            else:
                dict_func_info[key_save] = "False"
            pf.restore_rs_file(rs_original_content, add_path)
        
        pf.save_data_to_json(list_func_info, file_path)

print(f"{success_num} / {total_num}")